<?php
namespace wow\controller;

use \gnomephp\paypal\IpnListener;
use \wow\model\PayPalOrder;
use \gnomephp\doctrine\Doctrine;
use \wow\model\Donation;

/**
 * IPN path script.
 * Note default router rule when include core/paypal in routes is POST /index.php/paypal/ipn
 * 
 * @todo Implement me in your own way!
 * @author peec
 *
 */
class PayPalController extends \gnomephp\mvc\Controller{



	/**
	 * Process IPN script.
	 *
	 * @todo: replace me with how you want to confirm your order.
	 *
	 */
	public function index(){

		$listener = new IpnListener();

		if (\gnomephp\Configuration::get('donation','sandbox_enabled')){
			// tell the IPN listener to use the PayPal test sandbox
			$listener->use_sandbox = true;
		}

		// try to process the IPN POST
		try {
			$listener->requirePostMethod();
			$verified = $listener->processIpn();
				
			if ($verified){

				if (!$this->input->post){
					$this->logExit("Nothing to process.");
				}
				

				// Your paypal email ( The email that recieves the cash )
				$MY_PAYPAL_EMAIL = \gnomephp\Configuration::get('donation','receiver_email');
				
				
				// item_number
				$custom = $this->input->post->get('custom');
				
				$custom = explode(',', $custom);
				if (count($custom) != 3)$this->logExit("Unsufficient custom field aborting ... ");
				
				list($userid, $realmid, $charid) = $custom;
				
				$userid = (int)$userid;
				$realmid = (int)$realmid;
				$charid = (int)$charid;
				
				if (!$userid || !$realmid || !$charid)$this->logExit("Not formated custom field. Int abort.");
				
				$char = \wow\modelchar\Character::getCharacterById($realmid, $charid);
				
				if (!$char)$this->logWarning("Cant find character, aborting ...Realm: $realmid Char: $charid");
				
				$donation = Donation::getDonation($this->input->post->get('item_number'));
				
				
				if (!$donation)$this->logExit("No such item exist in our database.");
				
				
				
				// These should come from database of items you can order.
				$ITEM_COST = $donation->getPrice();
				$ITEM_COST_CURRENCY = $donation->getCurrency();




				// Checks if order is already processed.
				$txnId = $this->input->post->get('txn_id');
				if (PayPalOrder::orderProcessed((string)$txnId)){
					$this->logExit("Order is already processed.");
				}



				$payment_status = $this->input->post->get('payment_status');
				$receiver_email = $this->input->post->get('receiver_email');
				$mc_gross = $this->input->post->get('mc_gross');
				$mc_currency = $this->input->post->get('mc_currency');
				$payer_email = $this->input->post->get('payer_email');

				// Important check.
				if (
					$payment_status != 'Completed' ||
					$receiver_email != $MY_PAYPAL_EMAIL ||
					$mc_gross != $ITEM_COST ||
					$mc_currency != $ITEM_COST_CURRENCY
				){
					$this->logExit("We could not accept this order at this time.");
				}else{
					
					Doctrine::load();	
					$order = new PayPalOrder($txnId, $payer_email, $mc_gross, $mc_currency, $donation, $userid, $charid, $realmid);
					
					
					
					if (\gnomephp\Configuration::get('donation','send_items_auto')){
						$com = \wow\model\Soap::generateSoapFactory($realmid);
						
						if ($com && $char){
							if ($donation->getItems()){
								$this->logAuto($com->sendItems($char->name, $donation->getName(), $donation->getMessage(), $donation->getItemsAsArray()));
							}
							if ($donation->getMoney()){
								$this->logAuto($com->sendMoney($char->name, $donation->getName(), $donation->getMessage(), $donation->getMoney()));
							}
							
							$order->setItemRecieved(true);
						}else{
							$this->logWarning("Could not send automatic items / gold to player. You must send them manually.");
						}
					}
					
					Doctrine::getEM()->persist($order);
					Doctrine::getEM()->flush();
				}
			}else{
				$this->logExit("Not verified payment.");
			}

		} catch (\Exception $e) {
			$this->logExit("Exception: " . $e->getMessage());
		}

	}
	
	
	protected function logExit($msg){
		echo "ERROR";
		\gnomephp\Log::logMsg('--Donation IPN PAYPAL--: '.$msg, \gnomephp\Log::MODE_ALL);
		exit(0);
	}
	
	protected function logAuto($msg){
		\gnomephp\Log::logMsg('--Donation Auto Sender--: '.$msg, \gnomephp\Log::MODE_ALL);
	}

	protected function logWarning($msg){
		\gnomephp\Log::logMsg('--Donation Warning--: '.$msg, \gnomephp\Log::MODE_ALL);
	}
	

}